package com.zlcx.tz.live.processor.chain;

import com.zlcx.tz.live.processor.QuitRoomPostProcessor;
import com.zlcx.tz.live.utils.SpringContextHolder;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: anjl
 * @description: 计时自习室入座后，进行后续的操作，同步方法与主线程包装在同一个事物中，失败后，会回滚数据
 * 异步任务，如果出错，可以忍受，不影响主业务的运行
 * @data: 2020-09-27
 **/
@Component
public class QuitRoomPostProcessorChain<T> {

    private volatile List<QuitRoomPostProcessor> chain = null;

    public void processor(T t) {
        initChainIfNull();
        chain.forEach(processor -> processor.processor(t));
    }

    private void initChainIfNull() {
        if (Objects.isNull(chain)) {
            synchronized (QuitRoomPostProcessorChain.class) {
                if (Objects.isNull(chain)) {
                    chain = new ArrayList<>(SpringContextHolder.getApplicationContext().getBeansOfType(QuitRoomPostProcessor.class).values());
                    AnnotationAwareOrderComparator.sort(chain);
                }
            }
        }
    }
}
